package com.apes.bi.model;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Applet.CONST_TABLE_NAME)

public class Applet extends Model {
    public static final String CONST_TABLE_NAME = "bi_applet";

    @Id
    @Column(name = "id", length = 60)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "小程序编码")
    private String id;

    @Name
    @Comment("小程序名称")
    @Column(name = "name", length = 200)
    private String name;

    @Name
    @Comment("部件")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "widget_id", referencedColumnName = "id")
    private Widget widget;

    @Name
    @Comment("调用接口")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "widget_api_id", referencedColumnName = "id")
    private WidgetApi widgetApi;

    @Name
    @Comment("刷新周期（单位：分钟）")
    @Column(name = "period", length = 60, nullable = false)
    private long period = 0;

    @Name
    @Lob
    @Comment("元数据")
    @Column(name = "metadata", columnDefinition = "CLOB")
    private String metadata;

    @Name
    @OneToMany(mappedBy = "applet", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<AppletPostPermit> appletPostPermits = new HashSet<>();

    public Set<AppletPostPermit> getAppletPostPermits() {
        if(appletPostPermits == null) return null;
        for (AppletPostPermit item : appletPostPermits) {
            item.setApplet(this);
        }
        return appletPostPermits;
    }

    public void setAppletPostPermits(Set<AppletPostPermit> appletPostPermits){
        this.appletPostPermits.clear();
        if (appletPostPermits != null) {
            this.appletPostPermits.addAll(appletPostPermits);
        }
    }


    @Name
    @OneToMany(mappedBy = "applet", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<AppletUserPermit> appletUserPermits = new HashSet<>();

    public Set<AppletUserPermit> getAppletUserPermits() {
        if(appletUserPermits == null) return null;
        for (AppletUserPermit item : appletUserPermits) {
            item.setApplet(this);
        }
        return appletUserPermits;
    }

    public void setAppletUserPermits(Set<AppletUserPermit> appletUserPermits){
        this.appletUserPermits.clear();
        if (appletUserPermits != null) {
            this.appletUserPermits.addAll(appletUserPermits);
        }
    }

}
